package com.sz.hiling.Interceptor;


import com.sz.hiling.commons.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置请求头
        String head=request.getHeader("Authorization");
        //在请求头中要有zhiling字符串
        if (!StringUtils.isEmpty(head)&&head.startsWith("zhiling")){
            //取出第八个值
            String token=head.substring(7);
            //解密请求头带有加密内容
            Claims claims=JwtUtils.parseToken(token);
            System.out.println("key"+token);
            if (claims!=null){
                //将claim的内容放到请求作用域中
                String str=claims.getSubject()+claims.getId()+claims.getIssuedAt().toString();
                request.setAttribute("admins",str);
            }else {
                request.setAttribute("msg","你无权删除,因为token已经过期或不存在");
                request.getRequestDispatcher("/home.html").forward(request,response);
                return false;
            }
        }else {
            request.setAttribute("msg","你无权删除!!");
            request.getRequestDispatcher("/home.html").forward(request,response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
